package com.imooc.alllearning.util;

import org.springframework.util.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * 校验工具类
 * @Author: crowsjian
 * @Date: 2020/3/29 23:17
 */
public class ValidatorUtils {
    /**
     * 全局校验器
     */
    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * 参数校验
     * @param object
     * @param groups
     * @param <T>
     */
    public static <T> void validate(T object, Class...groups){
        Set<ConstraintViolation<T>> validate = validator.validate(object, groups);
        //校验不为空
        if(!CollectionUtils.isEmpty(validate)){
            StringBuilder stringBuilder = new StringBuilder();
            validate.forEach(tConstraintViolation -> {
                stringBuilder.append(tConstraintViolation.getMessage());
            });
            throw new RuntimeException(stringBuilder.toString());
        }
    }
}
